package com.action;

import com.bean.ResponseBean;
import com.pojo.Admin;
import com.pojo.AdminRole;
import com.service.AdminRoleService;
import com.service.UserService;
import com.util.PasswordUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserAction {

    @Autowired
    private UserService userService;

    @Autowired
    private AdminRoleService adminRoleService ;

    /**
     * 新增用户
     */
    @RequestMapping("/addUser")
    public ResponseBean addUser(@RequestBody Admin user){
        if(StringUtil.isNull(user.getUsername())) {
            return ResponseBean.error("请输入真实姓名") ;
        }
        if(StringUtil.isNull(user.getPassword())) {
            return ResponseBean.error("请输入密码") ;
        }
        long i = userService.countuName(user.getUsername());
        if(i==0){
            String password = user.getPassword();
            user.setPassword(PasswordUtil.jiami(password));
            user.setCreateTime(new Date());
            if (userService.save(user)) {
                AdminRole adminRole = new AdminRole() ;
                adminRole.setRoleId(user.getRole()) ;
                adminRole.setAdminId(user.getId()) ;
                adminRoleService.save(adminRole) ;
                return new ResponseBean(0, 1, "成功", "新增成功");
            } else {
                return new ResponseBean(1, 1, "失败", "新增失败");
            }
        }else{
            return new ResponseBean(2, 1, "该用户名已存在", "该用户已存在");
        }
    }

    /**
     * 重置用户密码
     */
    @RequestMapping("/resetPassword")
    public ResponseBean resetPassword(String id){
        Admin admin = new Admin();
        admin.setId(id);
        admin.setStatus(1);
        admin.setPassword(PasswordUtil.jiami("123456"));

        userService.updateById(admin);
        return new ResponseBean(200,1,"重置密码成功","");
    }


    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser")
    public ResponseBean deleteUser(String id){
        if ("1".equals(id)) {
            return new ResponseBean(500,"admin用户不能被删除","admin用户不能被删除");
        }
        if (userService.removeById(id)) {
            return new ResponseBean(200,"删除成功","删除成功");
        }
        return new ResponseBean(500,"删除失败","删除失败");
    }
}